package com.yr.ryjk.common;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.yr.ryjk.redis.JedisUtil;
import com.yr.ryjk.sms.SendSmsUtil;
import com.yr.ryjk.util.CheckCodeUtil;
import com.yr.ryjk.util.IDGenerator;
import com.yr.ryjk.util.JSONUtil;
/**
 * 公共接口
 * @author Rick
 *
 */
@Controller
@RequestMapping("/common")
@ResponseBody
public class CommonController {
	private Logger logger=Logger.getLogger(this.getClass());
	
	/**
	 * 输入手机号，请求向该手机发送短信验证码
	 * @param phone 手机号
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/checkcode",method=RequestMethod.GET)
	public Map<String, Object> getCheckcode(@RequestParam("phone") @NotNull String phone) {
		String checkcode=CheckCodeUtil.getRandomCode();
		JedisUtil.putPhoneCheckcodeMap(phone, checkcode);
		
		SendSmsUtil.sendSms(phone, "手机验证码为"+checkcode);  //sms
		return JSONUtil.getJSON(ErrorType.SUCCESS,checkcode);
	}
	
	/**
	 * 上传文件
	 * @param file 文件
	 * @return url
	 */
	@RequestMapping(value="upload",method=RequestMethod.POST,consumes={MediaType.MULTIPART_FORM_DATA_VALUE})
	@ResponseBody
	public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file){
		String fileName=file.getOriginalFilename();
		String suffix="";
		int index=fileName.lastIndexOf(".");
		if(index!=-1){
			suffix=fileName.substring(index);
		}
		String newFileName=IDGenerator.gen32UUID()+suffix;
		String path=Constant.WEB_SERVER_PATH+"/"+newFileName;
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path));
			String url=Constant.WEB_SERVER_URL+"/"+newFileName;
			return JSONUtil.getJSON(ErrorType.SUCCESS,url);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			return JSONUtil.getJSON(ErrorType.HANDLE_FILE_ERROR);
		}
	}
}